/**
 * created by 小卷毛, 2018/10/30
 * Copyright (c) 2018, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.sgcc.pda.mdrh.task.common_ui.helper

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Build
import android.os.Environment
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.annotation.RawRes
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

/**
 * 检查是否存在SDCard
 */
fun hasSdcard() = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED

/**
 * 将 view 转为 bitmap
 */
fun View.getBitmap(): Bitmap =
    Bitmap.createBitmap(
        width,
        height,
        Bitmap.Config.ARGB_8888
    ).let {
        draw(Canvas(it))
        it
    }

/**
 * 以数据流的方式将 Resources 下的图片显示，防止内存溢出
 */
@Suppress("DEPRECATION")
fun Context.getImgFromSD(iv: ImageView, @RawRes resID: Int) = kotlin.run {
    iv.background = BitmapDrawable(
        resources,
        BitmapFactory.decodeStream(
            resources.openRawResource(resID),
            null,
            BitmapFactory.Options().apply {
                inPreferredConfig = Bitmap.Config.RGB_565
                inPurgeable = true
                inInputShareable = true
            })
    )
}

/**
 * 读取 Assets 文件夹下的文件
 */
fun Context.getJsonFromAssets(fileName: String): String {
    val stringBuilder = StringBuilder()
    BufferedReader(
        InputStreamReader(
            assets.open(fileName),
            "UTF-8"
        )
    ).run {
        do {
            val line = readLine()
            if (line != null) stringBuilder.append(line)
            else break
        } while (true)
    }
    return stringBuilder.toString()
}

/**
 * 获取资源图片下的Uri路径
 */
fun Context.getResourcesUri(@DrawableRes resID: Int) =
    ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
            resources.getResourcePackageName(resID) + "/" +
            resources.getResourceTypeName(resID) + "/" +
            resources.getResourceEntryName(resID)

/**
 * 获取当前进程名
 */
fun Context.getProcessName() = kotlin.run {
    val pid = android.os.Process.myPid()
    val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    activityManager.runningAppProcesses.firstOrNull { it.pid == pid }?.processName.orEmpty()
}

/**
 * 判断网络是否可用
 */
@SuppressLint("MissingPermission")
@Suppress("DEPRECATION")
fun Context.isNetworkConnected() = kotlin.run {
    val connectivity = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val info = connectivity.allNetworkInfo
    info?.any { it.state == NetworkInfo.State.CONNECTED } ?: false
}

/**
 * 判断APP是否在前台运行
 */
fun Context.isRunningForeground() = kotlin.run {
    val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val appProcessInfos = activityManager.runningAppProcesses
    appProcessInfos.any {
        it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && it.processName == applicationInfo.processName
    }
}

/**
 * 获取App版本名称
 */
fun Context.getVersion(): String = kotlin.run {
    val info = packageManager.getPackageInfo(packageName, 0)
    info.versionName
}

/**
 * 获取App软件版本号
 */
fun Context.getVerCode() = kotlin.run {
    val info = packageManager.getPackageInfo(packageName, 0)
    @Suppress("DEPRECATION")
    info.versionCode
}

/**
 * 判断某个服务是否正在运行
 */
@Suppress("DEPRECATION")
fun Context.isServiceWork(serviceName: String) = kotlin.run {
    val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val serviceInfos = activityManager.getRunningServices(40)
    serviceInfos.any { it.service.className == serviceName }
}

/**
 * 复制字符串到剪切板
 */
fun Context.copyStringToClip(content: String) = kotlin.run {
    (getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
        ClipData.newPlainText("Label", content)
    )
}

/**
 * 根据包名判断是否有安装该App
 * 高德：com.autonavi.minimap
 * 百度：com.baidu.BaiduMap
 * 腾讯：com.tencent.map
 * 谷歌：com.google.android.apps.maps
 *
 * 主流应用商店对应的包名
 * GooglePlay：com.android.vending
 * 应用宝：    com.tencent.android.qqdownloader
 * 360助手：   com.qihoo.appstore
 * 百度助手：  com.baidu.appsearch
 * 小米商店：  com.xiaomi.market
 * 豌豆荚：    com.wandoujia.phoenix2
 * 华为市场：  com.huawei.appmarket
 * 淘宝助手：  com.taobao.appcenter
 * 安卓市场：  com.hiapk.marketpho
 * 安智市场：  cn.goapk.market
 *
 * 高德地图网页版 https://lbs.amap.com/api/uri-api/guide/travel/route
 * 百度地图网页版 http://lbsyun.baidu.com/index.php?title=uri/api/web
 *
 * @param packageName 包名
 */
fun Context.isAvilible(packageName: String) = kotlin.run {
    val pinfo = packageManager.getInstalledPackages(0)
    pinfo.any { it.packageName.equals(packageName, ignoreCase = true) }
}

/**
 * 屏幕宽度，单位：px
 */
fun Context.getScreenWidth() = kotlin.run {
    val manager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val display = manager.defaultDisplay
    val outMetrics = DisplayMetrics()
    display.getMetrics(outMetrics)
    outMetrics.widthPixels
}

/**
 * 屏幕高度，单位：px
 */
fun Context.getScreenHeight() = kotlin.run {
    val manager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val display = manager.defaultDisplay
    val outMetrics = DisplayMetrics()
    display.getMetrics(outMetrics)
    outMetrics.heightPixels
}

/**
 * 状态栏高度，单位：px
 */
fun Context.getStatusBarHeight() = kotlin.run {
    var statusBarHeight = 0
    val resourceId = resources.getIdentifier(
        "status_bar_height",
        "dimen",
        "android"
    )
    if (resourceId > 0)
        statusBarHeight = resources.getDimensionPixelSize(resourceId)
    statusBarHeight
}

/**
 * 获取32位uuid
 */
fun get32UUID() = get36UUID().replace("-".toRegex(), "")

/**
 * 生成唯一号
 */
fun get36UUID() = UUID.randomUUID().toString()

/**
 * 获取手机制造商
 */
fun getOSName() = Build.MANUFACTURER.orEmpty().toLowerCase(Locale.getDefault())
